import { getCurrentInstance } from 'vue'
import axios from 'axios'
import * as $CONST from '@/utils/constant'
import { ElMessage } from 'element-plus'
import {
  notice,
  fail,
  filterParams,
  isInlineParams,
  replaceUrlParams,
  getQueryObject,
  joinQueryUrl,
} from '@/utils/tools'

/**
 * 定义传入参数数据格式
 *
 * === 删除数据 ===
 * {
 *    key:['dataId1','dataId2']
 * }
 *
 */

/**
 * 定义返回的json数据格式
 *
 * === 分页数据 ===
 * {
 *    code:200,            --- 目前框架认为0和200都是成功状态
 *    message:'按业务自定义',
 *    data:{
 *      records:[{...},{...}],   --- 可按自己业务替换属性
 *      total:xx,          --- 可按自己业务替换属性
 *      size:xx,           --- 可按自己业务替换属性
 *      current:xx,        --- 可按自己业务替换属性
 *      pages:xx           --- 可按自己业务替换属性
 *    },
 * }
 *
 * === 列表数据 ===
 *
 * {
 *    code:200,
 *    message:'按业务自定义',
 *    data:[{..},{..}...]
 * }
 *
 * === 一条数据 ===
 *
 * {
 *    code:200,
 *    message:'按业务自定义',
 *    data:{...}
 * }
 *
 * === 无返回数据 ===
 *
 * {
 *    code:200,
 *    message:'按业务自定义',
 *    data: null
 * }
 *
 * === 树形结构 ===
 *
 * {
 *    code:200,
 *    message:'按业务自定义'
 *    data:[{
 *      prop:xx,
 *      ...
 *      children: [
 *         prop:xx,
 *         ...
 *         children:[...]
 *      ]
 *    },
 *    {
 *      prop:xx,
 *      ...
 *      children: [
 *         prop:xx,
 *         ...
 *         children:[...]
 *      ]
 *    }]
 * }
 *
 * // 环境的切换
 switch (process.env.NODE_ENV) {
  case 'development':
    axios.defaults.baseURL = 'http://localhost:8080'
    break
  case 'debug':
    axios.defaults.baseURL = 'http://www.ceshi.com'
    break
  case 'production':
    axios.defaults.baseURL = 'http://10.136.48.201:8080'
    break
  default:
    break
}
 *
 */

// 创建axios实例
const Service = axios.create({
  timeout: 60000, // 请求超时60秒
  withCredentials: true, // 表示跨域请求时是否需要使用凭证
})

// const CancelToken = axios.CancelToken

/*
function showDebugInfo(config) {
console.group('%cMethod::' + config.method + '::Url::' + config.url, 'color:red;font-size:12px;')
console.log('%c保存/更新/查看场合，传入的参数::', 'font-size:12px;')
console.log(config.hasOwnProperty('params') ? JSON.stringify(config.params) : JSON.stringify(config.data))
console.groupEnd()
}

function filterOauthData(config) {
let url = config.url
if (config.method === 'post' && isExistOauthApi(url)) {
// post请求的场合下，追加角色名称
}

if (config.method === 'get' && isExistOauthApi(url)) {
// get请求的场合下，追加角色名称
if (config.hasOwnProperty('params')) {
config.params['userCode'] = ''
} else {
config['params'] = {}
config.params['userCode'] = ''
}
}
return config
}*/

// // request拦截器
// Service.interceptors.request.use(
//   (config) => {
//     // 临时追加
//     // if (process.env.NODE_ENV !== 'production' && $store.state.user.account) {
//     //   config.headers.account = $store.state.user.account
//     // }
//     // if (process.env.NODE_ENV === 'production') {
//     //   const p = getQueryObject()
//     //   if (p.userCode) {
//     //     config.headers.account = p.userCode
//     //   } else {
//     //     config.headers.account = 'admin'
//     //   }
//     // } else {
//     //   if ($store.state.user.account) {
//     //     config.headers.account = $store.state.user.account
//     //   }
//     // }
//     // config.headers.Cookie =
//     //   'SSO_AS_UID=sevenzhang; SSO_AS_SUB_TICKET_LEGO=d3ad88b252c04f0f6de3b94213ce98ad0002560000; __hash__wa=20210816-1908-sevenzhang-2d80ec7c-d5e2-4662-b1ef-790118bb81d1; __hash__cache=2d80ec7c-d5e2-4662-b1ef-790118bb81d1; user-fingerprint-water-mark=20210816-1908-sevenzhang-2d80ec7c-d5e2-4662-b1ef-790118bb81d1'
//     const cancelToken = new axios.CancelToken(c => {
//       const { proxy } = getCurrentInstance(); // 或在全局挂载的 app 中访问
//       proxy.$cancels.push(c); // 将取消函数存入全局队列
//     });
//     config.cancelToken = cancelToken;
//     return config;
//   },
//   (error) => {
//     Promise.reject( error)
//   }
// )

// response拦截器
Service.interceptors.response.use(
  (response) => {
    // 生产环境未登陆跳转
    let resLowerCaseObj = {}
    for (let [k, v] of Object.entries(response.data)) {
      let lowerKey = k.toLowerCase()
      resLowerCaseObj[lowerKey] = v
    }
    if (resLowerCaseObj['errno'] === 101) {
      // token失效重新登陆
      try {
        let redirectHost = resLowerCaseObj['redirect'].split('?')[0]
        let redirectObj = getQueryObject(resLowerCaseObj['redirect'])
        redirectObj.jumpto = encodeURIComponent(location.href)
        let fullHref = joinQueryUrl(redirectHost, redirectObj)
        ElMessage.error(resLowerCaseObj['errmsg'])
        return location.replace(fullHref)
      } catch (e) {
        ElMessage.error(resLowerCaseObj['errmsg'])
        return location.replace(resLowerCaseObj['redirect'])
      }
    }
    if (resLowerCaseObj['errno'] && resLowerCaseObj['errno'] != 0) {
      if (resLowerCaseObj['errmsg'].indexOf('<a href') > -1) {
        return
      }
      notice(
        response.data.errno,
        response.data.errmsg || response.data['errMsg']
      )
    }
    // if (response.data.errno === 101) {
    //   let urlParam = getQueryObject(response.data.redirect)
    //   let jumpToUrl = urlParam.jumpto.substring(7)
    //   urlParam.jumpto = `http://onepeace.${jumpToUrl}`
    //   let directive = joinQueryUrl(
    //     'http://mis-auth.prox.com/auth/sso/login',
    //     urlParam
    //   )
    //   ElMessage.error(response.data.errmsg)
    //   window.location.replace(directive)
    // }
    // redirect: "http://mis-auth.prox.com/auth/sso/login?app_id=2560&jumpto=http%3A%2F%2Flego.intra.prox.com%2F&version=1.0"
    return response.data
  },
  (error) => {
    if (error.message && error.message.includes('timeout')) {
      fail($CONST.MSG_SYS_TIME_OUT)
      return Promise.reject(error)
    }

    if (!error.response) {
      // eslint-disable-next-line no-proto
      if (error.__proto__.__CANCEL__) {
        return
      }
      fail($CONST.MSG_SYS_ERR)
      return Promise.reject(error)
    }

    switch (error.response.status) {
      // http status handler
      case 404:
        fail($CONST.MSG_SYS_404)
        break
      case 500:
        fail($CONST.MSG_SYS_ERR)
        break
      case 503:
        fail($CONST.MSG_SYS_503)
        break
    }

    return Promise.reject(error)
  }
)

const $http = {}
$http.$service = Service
$http.$axios = axios
$http.get = function (url, params = {}) {
  if (isInlineParams(url)) {
    // 严格遵循restful标准的url的场景
    url = replaceUrlParams(url, params)
    params = {}
  }
  return Service({
    url: url,
    method: 'get',
    params: filterParams(params),
  })
}
$http.post = function (url, data = {}) {
  return Service({
    url: url,
    method: 'post',
    data: data,
  })
}
$http.put = function (url, data = {}) {
  return Service({
    url: url,
    method: 'put',
    data: data,
  })
}
$http.delete = function (url, data = {}) {
  return Service({
    url: url,
    method: 'delete',
    data: data,
  })
}
export default $http
